package com.crm.services;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.crm.model.jdao.IDetailedDemandDAO;
import com.crm.model.pojo.Competitor;
import com.crm.model.pojo.Contact;
import com.crm.model.pojo.Customer;
import com.crm.model.pojo.DetailedDemand;
import com.crm.model.pojo.SalesOpportunity;

/**
 * 客户需求services
 * @author 飞鱼
 *
 */
@Service
public class DetailedDemandService {

	@Autowired
	private IDetailedDemandDAO DetailedDemandDAO;
	@Autowired
	private DetailedDemandService dds;
	@Autowired
	private DictionaryServices ds;
	@Autowired
	private SalesOpportunityServices sos;
	@Autowired
	private UserServices us;
	private static int count=0;
	/**
	 * 查询全部所有详尽需求
	 * @return 
	 */
	public List<DetailedDemand> queryByAll(int pageNumber,int pageContent,String[] DId) {
		Sort sort=Sort.by(Direction.DESC, "demandId");
		Pageable pageable =PageRequest.of(pageNumber,pageContent,sort);	
		//查询条件构造
		 Specification<DetailedDemand> spec=new Specification<DetailedDemand>(){

			@Override
			public Predicate toPredicate(Root<DetailedDemand> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				// TODO Auto-generated method stub
				//Path<Object> state=root.get("state");
				List<Predicate> list=new ArrayList<>();
				System.out.println("ss的DId:"+DId);
					if(DId.length==0) {
						list.add(cb.equal(root.get("state").as(Integer.class), 1));
					}
					int i=0;
					for (String str : DId) {
						System.out.println("str:"+str);
						if("全部数据".equals(str)) {
							 list.add(cb.equal(root.get("state").as(Integer.class), 1));	
						}
						if("重要程度".equals(str)) {
							System.out.println("触发了重要程度数据筛选");
							 list.add(cb.equal(root.get("importance_degree").as(Integer.class), DId[i+1]));							
						}
						if("客户名称".equals(str)) {
							System.out.println("触发了模糊客户名称数据筛选");	
							//cb.countDistinct(root.join("customer").get("custName")));
							if("不分组".equals(DId[i+1])) {
								list.add(cb.like(root.join("customer").get("custName").as(String.class),"%"+DId[i+2]+"%"));									
							}else {
								list.add(cb.like(root.join("customer").get("custName").as(String.class),"%"+DId[i+1]+"%"));
							    query.groupBy(root.get("customer").as(Customer.class));
							}

						}
						if("需求主题".equals(str)) {
							if("不分组".equals(DId[i+1])) {
								list.add(cb.like(root.get("dedTheme").as(String.class),"%"+DId[i+2]+"%"));									
							}else {
								list.add(cb.like(root.get("dedTheme").as(String.class),"%"+DId[i+1]+"%"));
							   // query.groupBy(root.get("dedTheme").as(Customer.class));
							}
						}
						if("机会主题".equals(str)) {
							System.out.println("触发了模糊机会主题数据筛选");	
							if("不分组".equals(DId[i+1])) {
								list.add(cb.like(root.join("salesOpportunity").get("salTheme").as(String.class),"%"+DId[i+2]+"%"));									
							}else {
								list.add(cb.like(root.join("salesOpportunity").get("salTheme").as(String.class),"%"+DId[i+1]+"%"));	
								query.groupBy(root.get("salesOpportunity").as(SalesOpportunity.class));
							}							
													
						}
						i++;
					}

		        Predicate[] p = new Predicate[list.size()];
		        System.out.println("-----------------------------------------");
			    query.where(list.toArray(p));
				return query.getRestriction();
			}
			 
		 };
		 
		Page<DetailedDemand> page=DetailedDemandDAO.findAll(spec,pageable);
				
		System.out.println("总记录数："+page.getTotalElements());
		count=(int) page.getTotalElements();
		List<DetailedDemand> list=page.getContent();
		return list;		 
	}
	
	/**
	 * 统计对象个数
	 * @return
	 */
	public int queryByCount() {
		return count;
		
	}
	/**
	 *将list的数据转换成JsonArray的数据
	 * @return
	 */
	public JSONArray ListTransJSONArray(int pageNumber,int pageContent,String[] DId) {
		JSONArray array =new JSONArray();
		List<DetailedDemand> list=dds.queryByAll(pageNumber,pageContent,DId);
		for (DetailedDemand salesOpportunity : list) {
		//System.out.println("salesOpportunity:"+salesOpportunity.getDedTheme());
			JSONObject obj = new JSONObject();		
			array.add(toJSONObject1( obj,salesOpportunity));
	}
		return array;
	}
	/**
	 * 通过需求id查找客户需求
	 * @param demand_Id
	 * @return
	 */
	public JSONObject findByDemand_Id(Integer demand_Id) {
		DetailedDemand	sale=DetailedDemandDAO.queryByDemandId(demand_Id);
		JSONObject obj = new JSONObject();	
		return toJSONObject2(obj,sale);
		
	}
	/**
	 * 销售机会转JSONObject
	 * @param obj
	 * @param salesOpportunity
	 * @return
	 */
	public JSONObject toJSONObject1(JSONObject obj,DetailedDemand salesOpportunity) {
		
		obj.put("demandId", salesOpportunity.getDemandId());//需求id
		obj.put("custName", salesOpportunity.getCustomer().getCustName()+"");//客户名
		obj.put("salTheme", salesOpportunity.getSalesOpportunity().getSalTheme()+"");//销售机会主题名
		if(null!=salesOpportunity.getDedProvidersId()) {
			obj.put("dedProvidersId",  us.findByUId(salesOpportunity.getDedProvidersId()).getUName()+"");//需求提供人id，名字
			obj.put("userId", us.findByUId(salesOpportunity.getDedProvidersId()).getUId()+"");
		}else {
			obj.put("dedProvidersId","");//需求提供人id，名字		
			obj.put("userId","");
		}

		obj.put("dedContent", salesOpportunity.getDedContent());//需求内容
		if(salesOpportunity.getRecordingTime()!=null) {
			obj.put("recordingTime", salesOpportunity.getRecordingTime().toString());//记录时间
		}
		
		obj.put("importanceDegree", ds.findByDictId(salesOpportunity.getImportanceDegree()));//重要程度
		obj.put("detailedFile", salesOpportunity.getDetailedFile());//上传文件
		obj.put("dedTheme", salesOpportunity.getDedTheme());//需求主题
		return obj;
	}
	
	
	/** 销售机会转JSONObject,单一saleOpp
	 * @param obj
	 * @param Competitor
	 * @return
	 */
	public JSONObject toJSONObject2(JSONObject obj,DetailedDemand Competitor) {
		/*
		obj.put("salId", Competitor.getSalId());
		obj.put("salTheme", Competitor.getSalTheme());
		obj.put("customerName", Competitor.getCustomer().getCustName());
		obj.put("customerId", Competitor.getCustomer().getCustId()+"");			
		obj.put("starStandard",Competitor.getStarStandard()+"");
		
		obj.put("salTypelabel", ds.findByDictId(Competitor.getSalType()));
		obj.put("salTypeValue", Competitor.getSalType());
		
		//obj.put("sotlId", Competitor.getSotlId());	
		if(Competitor.getSotlDate()!=null) {
			obj.put("sotlDate",Competitor.getSotlDate().toString());			
		}		
		obj.put("sotlMoney", Competitor.getSotlMoney());
		//
		obj.put("custDemand", Competitor.getCustDemand());
		
		obj.put("salStageStop", Competitor.getSalStageStop()+"天");		
		obj.put("salState", Competitor.getSalState()+"");		
		obj.put("salPossibilitylabel", ds.findByDictId(Competitor.getSalPossibility()));

		obj.put("sotlId", ss.findByUserName(Competitor.getSotlId()));
		obj.put("salStagelabel", ds.findByDictId(Competitor.getSalStage()));
		obj.put("salStageNotes", Competitor.getSalStageNotes());
		
		obj.put("salSourcelabel", ds.findByDictId(Competitor.getSalSource()));
		if(Competitor.getContact()!=null) {
			obj.put("contactName", Competitor.getContact().getConName()+"");			
		}else {
			obj.put("contactName","");				
		}
		obj.put("contactId", Competitor.getContact().getConId());
		*/
		if(null!=Competitor.getDemandId()) {
			obj.put("demandId", Competitor.getDemandId());//需求id			
		}else {
			obj.put("demandId", "");//需求id			
		}
		if(null!=Competitor.getDedProvidersId()) {
			obj.put("dedProvidersId",  us.findByUId(Competitor.getDedProvidersId()).getUName()+"");//需求提供人id，名字			
		}else {
			obj.put("dedProvidersId", "");//需求提供人id，名字					
		}

		obj.put("dedContent", Competitor.getDedContent());//需求内容
		if(Competitor.getRecordingTime()!=null) {
			obj.put("recordingTime", Competitor.getRecordingTime().toString());//记录时间
		}
		
		obj.put("importanceDegree", ds.findByDictId(Competitor.getImportanceDegree()));//重要程度
		obj.put("detailedFile", Competitor.getDetailedFile());//上传文件
		obj.put("dedTheme", Competitor.getDedTheme());//需求主题
		obj.put("salesOpportunityName",Competitor.getSalesOpportunity().getSalTheme());
		obj.put("salesOpportunityId", Competitor.getSalesOpportunity().getSalId());
		//obj.put("customer", Competitor.getCustomer().getCustName());
		obj.put("customerName", Competitor.getCustomer().getCustName());
		obj.put("customerId", Competitor.getCustomer().getCustId()+"");	
		return obj;
	}
	/**
	 * 将list的数据转换成JsonArray的数据,用于页面搜索查询销售机会主题名称信息
	 * 
	 * @return
	 */
	public JSONArray ListTransJSONArray3(List<DetailedDemand> list) {
		JSONArray array = new JSONArray();
		for (DetailedDemand salesOpportunity : list) {
			// System.out.println("salesOpportunity:"+salesOpportunity);
			JSONObject obj = new JSONObject();
			obj.put("value", salesOpportunity.getSalesOpportunity().getSalTheme());
			array.add(obj);
		}
		return array;
	}	
	/**
	 * 将list的数据转换成JsonArray的数据,用于页面搜索查询客户信息
	 * 
	 * @return
	 */
	public JSONArray ListTransJSONArray1(List<DetailedDemand> list) {
		JSONArray array = new JSONArray();
		for (DetailedDemand Competitor : list) {
			// System.out.println("Competitor:"+Competitor);
			JSONObject obj = new JSONObject();
			
			obj.put("value", Competitor.getCustomer().getCustName());
			obj.put("label1", Competitor.getCustomer().getCustId());
			array.add(obj);
		}
		return array;
	}	
	/**
	 * 将list的数据转换成JsonArray的数据,用于页面搜索查询需求主题信息
	 * 
	 * @return
	 */
	public JSONArray ListTransJSONArray4(List<DetailedDemand> list) {
		JSONArray array = new JSONArray();
		for (DetailedDemand Competitor : list) {
			// System.out.println("Competitor:"+Competitor);
			JSONObject obj = new JSONObject();
			
			obj.put("value", Competitor.getDedTheme());
			array.add(obj);
		}
		return array;
	}
	/**
	 * 确认需求主题是否重复
	 * @param salTheme
	 * @return 
	 */
	public Integer findByDedTheme(String salTheme) {
		DetailedDemand sale=DetailedDemandDAO.findByDedTheme(salTheme);
		if(sale!=null) {
			return sale.getDemandId();
		}
		return 0;
	}
	
	/**
	 * 添加单个客户需求
	 * @param sale
	 */
	public int save(DetailedDemand sale) {
		if(sale.getSalesOpportunity().getSalStage()<1326) {
			sale.getSalesOpportunity().setSalStage(1326);
		}
		DetailedDemandDAO.save(sale);
		return 1;
	}
	/**
	 * 删除单个销售机会
	 * @param salId
	 * @return
	 */
	public void Delete(Integer salId) {
		DetailedDemand sal=DetailedDemandDAO.findById(salId).get();
		sal.setState(0);
		DetailedDemandDAO.save(sal);		
	}
}
